<?php

namespace frontend\controllers;

use yii;
use yii\db\Query;
use common\models\Product;
use common\models\ProductGallery;
use common\components\Myhelpers;
use common\models\Order;
use common\models\Brand;
use common\models\Region;
use common\models\Company;
use common\models\Category;
use yii\data\Pagination;
use yii\web\BadRequestHttpException;

class ProductController extends FController
{
	  public $enableCsrfValidation = false;

	  //商品列表页
    public function actionIndex()
    {
      $cache = Yii::$app->cache;
      //显示最近浏览记录
      $recently_pid = Yii::$app->request->cookies->getvalue('recently_pid');
      $scan_list = [];
      if($recently_pid){
          //分配浏览记录到页面
          foreach ($recently_pid as $k => $v) {
            $scan_list[$k] = Product::find()
                  ->select('id,name,product_price,price_unit,spec,img_url')
                  ->where(['id'=>$v])
                  ->asArray()
                  ->one();
                  //var_dump($scan_list);
          }
      }

      //筛选默认条件
      $where = "a.is_show=1";
      
      $brand_id = (int)Yii::$app->request->get('bid');
      if($brand_id){
        $where .= " AND a.brand_id = ".$brand_id;
      }
      $cate_id = (int)Yii::$app->request->get('lv2');
      if($cate_id){
        $where .= " AND b.category_id = ".$cate_id;
      }
      $pro_name = Myhelpers::RemoveXSS(Yii::$app->request->get('name'));
      $params = [];
      if($pro_name){
        $where .= " AND (a.name like :pro_name OR c.name like :pro_name OR a.title like :pro_name OR a.keywords like :pro_name)";
        $params = [':pro_name' => '%'.$pro_name.'%'];
      }

      //如果选择了一级或者2级分类，将选择的结果分配到页面去绑定、并查询对应的3级列表而不是默认的全部3级分类
      $lv['lv1']= '';
      $lv['lv1']['id']= '';
      $lv['lv1']['name']= '';
      $lv['lv2']= '';
      $lv['lv2']['id']= '';
      $lv['lv2']['name']= '';
      $lv1 = (int)Yii::$app->request->get('lv1');
      $lv2 = (int)Yii::$app->request->get('lv2');
      if($lv1){
        $lv['lv1']['id'] = $lv1;
        $lv['lv1']['name'] = Category::find()->select('name')
                           ->where(['is_show'=>1,'level'=>1,'id'=>$lv1])->scalar();

      //如果1级分类存在，列表应该是parent_id = 1 的数据
      $lv['lv2']['list'] = Category::find()->select('id,name')
                       ->where(['is_show'=>1,'level'=>2,'parent_id'=>$lv1])
                       ->orderby('sort_number asc,id asc')
                       ->asArray()
                       ->all();                           
        if($lv2){
          $lv['lv2']['id'] = $lv2;
          $lv['lv2']['name'] = Category::find()->select('name')
                           ->where(['is_show'=>1,'level'=>2,'id'=>$lv2])->scalar();
        
        //如果1和2级分类都选了，那就查询对应的3级列表                          
          /*$category_list = Category::find()
            ->select('id,name')
            ->where(['is_show'=>1,'level'=>3,'parent_id'=>$lv2])
            ->asArray()
            ->all();*/
        }
        if(!$lv2){
          $where .= " AND b.category_id = ".$lv1;
        }
      }

    	$product = (new Query)
    			->from('product AS a')
  				->select('a.id,a.name,a.title,a.price_unit,a.sort_numer,a.product_price,a.spec,a.img_url')
  				->where($where,$params)
  				->leftJoin('product_category AS b','b.product_id = a.id')
  				->leftJoin('category AS c','c.id = b.category_id')
  				->distinct()
  				/*->asArray()*/;

    	//框架自带的跳转分页
    	$pages = new Pagination(
    		[
	    		'totalCount' => $product->count(),
	    		/*'pageSize'=>'3',*/
	    		'defaultPageSize' => 40,		//------自行设置每页显示的商品数量
	    		'validatePage' => false,
    		]
    	);

    	$proruct_sum = $product->count();
    	$page_sum = intval(($product->count()+$pages->limit-1)/$pages->limit);

    	$product_list = $product->limit($pages->limit)->offset($pages->offset)->orderby('a.sort_numer asc,a.id asc')->all();

    	//循环查询规格和已售数量
    	foreach ($product_list as $k => $v) {
   			//已售
   			$product_list[$k]['sale_sum'] = (new Query())
	   				->select('sum(b.product_num)')
	   				->from('order_product AS a')
	   				->where(['a.product_id'=>$v['id'],'b.order_status'=>4,'b.pay_status'=>2,'b.shipping_status'=>3])
	   				->leftJoin('order AS b','b.id = a.order_id')
	   				->scalar();
    	}
    	//var_dump($product_list);

    	// 尝试从缓存中取回 $data 
      $brand_list = $cache->get('brand_list');

      if ($brand_list === false) {

          //查询品牌、
          $brand_list = Brand::find()->select('id,name')->where(['is_show'=>1])->asArray()->all();
          $cache->set('brand_list', $brand_list);
      }

    	//商品分类列表、默认选择几个，选择了一级二级分类之后这里将改为对应的三级分类
    	$category_list = Category::find()->select('id,name')->where(['is_show'=>1,'level'=>3])->asArray()->all();

    	//商品分类列表----一级分类
    	$level_1 = Category::find()
    			->select('id,name')
    			->where(['is_show'=>1,'level'=>1])
    			->orderBy('sort_number')
    			->asArray()
    			->all();

    	//根据选择的一级分类的id选择对应的二级分类
    	$level_1_id = Yii::$app->request->post('level_1_id');
    	if($level_1_id){
	    	$level_2 = Category::find()
	    			->select('id,name')
	    			->where(['is_show'=>1,'level'=>2,'parent_id'=>$level_1_id])
	    			->orderBy('sort_number')
	    			->asArray()
	    			->all();

	    	return json_encode($level_2);
    	}
    	
    	//根据选择的二级分类的id选择对应的三级分类
    	/*$level_2_id = Yii::$app->request->post('level_2_id');
    	if($level_2_id){
	    	$level_3 = Category::find()
	    			->select('id,name')
	    			->where(['is_show'=>1,'level'=>3,'parent_id'=>$level_2_id])
	    			->orderBy('sort_number')
	    			->asArray()
	    			->all();

	    	return json_encode($level_3);
    	}*/

      //修改页面标题
      Yii::$app->view->params['page']['page_title'] = '商品列表 - ' . $this->w_config['website_name'];
    	return $this->render('index',[
    		'product_list' => $product_list,
    		'pages' => $pages,
    		'page_sum' => $page_sum,
    		'product_sum' => $proruct_sum,
    		'brand_list' => $brand_list,
    		'level_1' => $level_1,
    		'category_list' => $category_list,
    		'cate_id' => $cate_id,
    		'brand_id' => $brand_id,
    		'lv' => $lv,
        'scan_list' => array_reverse($scan_list),
        'pro_name' => $pro_name,
    	]);
    }

    //商品详情页面
 	  public function actionView()
    {
		  $id = (int)Yii::$app->request->get('id');
      $uid = Yii::$app->user->id;

      //查询收藏表，判断该商品是否为已经收藏的
      $is_collect = (new Query())
                  ->select('id')
                  ->from('collection')
                  ->where(['user_id'=>$uid,'product_id'=>$id])
                  ->count();
   		$model = new product();

   		//当前商品的信息
   		$product = Product::findOne($id);

      if(!$product){
        throw new BadRequestHttpException('您所链接的商品不存在');
      }
   		//商品相册
   		$where = ['product_id'=>$id,'is_show'=>1];
   		$product_img = ProductGallery::find()
   				->select('img_url,title,desc')
   				->where($where)
          ->limit(4)
          ->orderBy('id desc')
   				->all();

   		//配送方式
   		$supply = Product::itemAlias('supply',$product->supply);
   		$product->supply = $supply;

   		//寄送样品
   		/*$send_sample = Product::itemAlias('send_sample',$product->send_sample);
   		$product->send_sample = $send_sample;*/


   		//成交数量和成交记录
   		$order = (new Query())
   				->select('b.product_num,b.order_fee,b.create_time,c.username')
   				->from('order_product AS a')
   				->where(['a.product_id'=>$id,'b.order_status'=>4,'b.pay_status'=>2,'b.shipping_status'=>3])
   				->leftJoin('order AS b','b.id = a.order_id')
   				->leftJoin('user AS c','c.id = b.user_id');

		  //订单总记录数
   		$product->suc_amount = $order->count();


   		//AJAX分页
  		$order_per = 2;	//每页需要显示的条数

  		$order_page = Yii::$app->request->post('page')?Yii::$app->request->post('page'):1;

  		$order_yema = /*$order_page==1?$order_page:*/($order_page-1)*$order_per;

    	$order_list = $order->limit($order_per)->offset($order_yema)->orderBy('b.id DESC')->all();

    	$page_sum = intval(($product->suc_amount+$order_per-1)/$order_per);
    	$last_page = $page_sum==0?1:$page_sum;

    	$page['per'] = $order_per;
    	$page['yema'] = $order_yema;
    	$page['curr_page'] = $order_page;
    	$page['last_page'] = $last_page;

    	if(Yii::$app->request->post('name') == 'order_list'){
    		foreach ($order_list as $key => $value) {
    			$order_list[$key]['username'] = mb_substr($order_list[$key]['username'],0,6,'utf-8').'*****';
    		}
    		return json_encode($order_list);
    	}

   		//买家还在看的列表、随机从商品表中读取几个
   		$product_others = (new Query())
				   		->select('a.id,a.name,a.product_price,a.price_unit,a.img_url')
				   		->from('product AS a')
				   		->where(['a.is_show'=>1])
				   		->andWhere(['!=','a.id',$id])
				   		->groupBy('a.id')
				   		->distinct()
				   		->all();
  		//var_dump($product_others);

  		//配送地区三级联动
  		$province = Region::find()
  				->select('id,name')
  				->where(['level'=>1])
  				->asArray()
  				->orderBy("char_length(name)")
  				->all();
  		//var_dump($province);

  		//用传过来的省的ID查询下级城市
  		$province_id = Yii::$app->request->post('province_id');

  		if($province_id){
  			$city = Region::find()
  					->select('id,name')
  					->where(['level'=>2,'parent_id'=>$province_id])
  					->asArray()
  					->all();
  			return json_encode($city);
  		}

  		//用传过来的市的ID查询下级地区
  		$city_id = Yii::$app->request->post('city_id');

  		if($city_id){
  			$town = Region::find()
  					->select('id,name')
  					->where(['level'=>3,'parent_id'=>$city_id])
  					->asArray()
  					->all();
  			return json_encode($town);
  		}

      //添加收藏和取消收藏
      $product_id = Yii::$app->request->post('cid');
      $colect_action = Yii::$app->request->post('action');
      if($product_id){
        if(Yii::$app->user->isGuest){
          return $res = -1;
          //return $this->redirect(['site/login']);=========提示信息页面跳转最好
        }
        if($colect_action == 1){  //1是添加
          $res = Yii::$app->db->createCommand()
              ->insert('collection',[
                  'user_id' => $uid,
                  'product_id' => $product_id,
                  'create_time' => date('Y-m-d H:i:s')
                ])
              ->execute();
        }else if($colect_action == 0){
          $res = Yii::$app->db->createCommand()
               ->Delete('collection', ['user_id'=>$uid,'product_id'=>$product_id])
               ->execute();
        }
        return $res;
      }

      //每次访问本方法，将浏览的商品id保存到cookie里面，最近浏览提取出来

      $recently_pid = Yii::$app->request->cookies->getvalue('recently_pid');
      $scan_list = [];
      if($recently_pid){
          //分配浏览记录到页面
          foreach ($recently_pid as $k => $v) {
            if($v!=$id){
              $scan_list[$k] = Product::find()
                  ->select('id,name,product_price,price_unit,spec,img_url')
                  ->where(['id'=>$v])
                  ->asArray()
                  ->one();
                  //var_dump($scan_list);
            }
          }
          if(!in_array($id,$recently_pid) && $product){
            array_push($recently_pid, $id);
          }
      }else{
          $recently_pid[] = $id;
      }
      //var_dump();

      if(count($recently_pid)>50){
          array_shift($recently_pid);   //如果COOKIE里面的浏览记录大于10条，删除第一条
      }
      $cookies = Yii::$app->response->cookies;
      $cookies->add(new \yii\web\Cookie([
          'name' => 'recently_pid',
          'value' => $recently_pid,
      ]));

      //品牌和供应商
      $bname = Brand::findOne($product['brand_id'])->name;
      $comname = Company::findOne($product['company_id'])->company_name;

      $seo_title = $product['name'].'-'.$bname.'-'.$comname.'-';
      $seo_keys = $product['name'].','.$bname.','.$comname.',';

      $search = array(" ","　","\n","\r","\t","&nbsp;");
      $replace = array("","","","","");
      $seo = str_replace($search, $replace, strip_tags($product['des']));
      $seo_des = mb_substr($seo, 0, 200, 'UTF-8');

  		//修改页面标题
      Yii::$app->view->params['page']['page_title'] = $seo_title.$this->w_config['website_name'];
      Yii::$app->view->params['page']['page_keywords'] = $seo_keys.$this->w_config['website_name'];
      Yii::$app->view->params['page']['page_description'] = $seo_des;
      

      return $this->render('view',[
      	'model' => $model,
      	'product' => $product,
      	'product_img' => $product_img,
      	'order_list' => $order_list,
      	'page' => $page,
      	'product_others' => $product_others,
      	'province' =>$province,
        'is_collect' =>$is_collect,
        'scan_list' => array_reverse($scan_list),
      ]);
    }

 
}
